package edu.hcmus.sow.dao;

import java.util.Calendar;
import java.util.Date;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataAccessException;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;

import edu.hcmus.sow.domain.Task;

/**
 * DAO to manage Task entities.
 * 
 */
@Repository("TaskDAO")
@Transactional
public class TaskDAOImpl extends AbstractHibernateDAO<Task, Integer> implements TaskDAO {
	@Autowired
	ProjectDAO projectDAO;

	//
	//Task common
	//
	public List<Task> getTaskListByProject(Integer projectID)throws DataAccessException {
		// Get task list by Project object
		String  queryString = "Select task FROM Task as task " +
				"join fetch task.userByCreatedBy u " +
				"join fetch task.taskStatus stt " +
				"join fetch task.project " +
				"WHERE task.project.id = ? AND (task.taskStatus.id = 2 OR task.taskStatus.id =  4)";
		List<Task> list = executeQuery(queryString, projectID);
		
		return list;
	}
	
	
	public List<Task> getCompletedTaskListByProject(Integer projectID, Integer time)throws DataAccessException {

		//get now
		Date dateNow = Calendar.getInstance().getTime();
		
		// Get task list by Project object
		String  queryString = null;
		List<Task> list = null;
		
		if (time != -1){
			queryString = "Select task FROM Task as task " +
					"join fetch task.userByCreatedBy tu " +
					"join fetch task.project tpro " +
					"WHERE task.project.id = ? AND task.taskStatus.name='Finished' AND DATEDIFF(?,task.updatedDate)  <= ?)";
			 list = (List<Task>)executeQuery(queryString, projectID, dateNow, time);
		}
			
		else{
			queryString = "Select task FROM Task as task " +
					"join fetch task.userByCreatedBy u " +
					"join fetch task.project tpro " +
					"WHERE task.project.id = ? AND task.taskStatus.name='Finished'";
			list = (List<Task>)executeQuery(queryString, projectID);
		}
		return list;
	}
	
	//
	//Task detail
	//
	public Task findByID(Integer id)throws DataAccessException{
		String queryString = "from Task t " +
				"join fetch t.userByCreatedBy u " +
				"join fetch t.userByAssignedTo a " +
				"join fetch t.project " +
				"WHERE t.id = ?";
		List <Task> list = executeQuery(queryString, id);
		return list.size() == 0 ? null : list.get(0);
	}
	
	
	
}
